<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2022/04/22
//      |_|                                         | TpMeCMS

namespace app\cms\controller;

use app\cms\controller\Cms;
use think\Db;
use think\Cookie;
use EasyWeChat\Factory;
use think\Session;
use think\Config;


class Wechat extends Cms
{

    protected $noNeedLogin = ['*']; //自己需要写的方法 这个是不需要登陆的其他则为需要登陆
    protected $noNeedRight = '*';
    protected $layout = '';


    public function _initialize()
    {
        parent::_initialize();

        //需要登陆的方法 加入到里面
        $NeedLogin = ['index', 'add_evaluate', 'add_line']; //根据需求更改
        foreach ($NeedLogin as $action) {
            if ($action == $this->request->action()) {
                if (!$this->auth->isLogin()) {
                    // $this->error('请登陆');
                    $this->redirect('/cms/user/wx_login');
                }
            }
        }



        $this->config = [
            'app_id' => Config('site.wx_app_id'), //微信公众号的appid
            'secret' => Config('site.wx_secret'), //微信公众号的密钥
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            // 'response_type' => 'array',
            'oauth' => [
                'scopes'   => ['snsapi_login'],//['snsapi_userinfo'],
                'callback' => '/cms/wechat/wx_callback',
            ],
        ];

        $this->app = Factory::officialAccount($this->config);
    }

    /**
     * 首页
     *
     * @return void
     */
    public function index()
    {
        return $this->view->fetch();
    }



    //首页
    public function pc($wx_token=null)
    {
    
        if(!$this->auth->isLogin()){
            $res = Db::name('pc_login')->where('token',$wx_token)->find();
            if(!$res){
                if(!$wx_token)  $this->redirect('/cms/wechat/qr_login');
                $this->error('已失效，请刷新扫码登陆');
            }
            if($res['status']=='2'){
                
                $user = Db::name('user')->where('wx_openid',$res['openid'])->find();
                $this->auth->direct($user['id']);
                // Session::set('id',$this->auth->id);
    
                Cookie::set('uid', $this->auth->id, 3600);
                Cookie::set('token', $this->auth->getToken(), 3600);
                
            }
        }
        $this->update_app_id();
        
      
        $this->view->assign('user', $this->auth->getUserInfo());
        return $this->view->fetch();
    }

    /**
     * Api在线调试
     *
     * 
     * @return void
     */
    public function api()
    {
        if(!$this->auth->isLogin()){
            $this->redirect('/cms/wechat/pc');
            exit();
        }
        $this->view->assign('user', $this->auth->getUserInfo());
        return $this->view->fetch();
    }

    /**
     * 更新app_id
     *
     * @return void
     */
    protected function update_app_id()
    {
        if(strlen($this->auth->app_id)>10){

        }else{
            $data['app_id'] = md5($this->auth->id);
            $data['key'] = md5($this->auth->wx_openid);
            $res = Db::name('user')->where('id',$this->auth->id)->update($data);
        }
    }

    /**
     * PC上的二维码登陆界面
     *
     * @return void
     */
    public function qr_login()
    {
        if($this->auth->isLogin()){
            $this->redirect('/cms/wechat/pc');
            exit();
        }
        $data['ip'] = $this->request->ip();
        $data['time'] = time();
        $id = Db::name('pc_login')->insertGetId($data);
        $token = md5($id);
        Db::name('pc_login')->where('id',$id)->update(['token'=>$token]);

        //创建二维码
        $qr = new \addons\qrcode\controller\Index;
        
        $url = $qr->get_qr($this->request->domain().'/cms/wechat/pc_callback?wx_token='.$token);
           
        $this->view->assign('qr', $url);//二维码
        $this->view->assign('token', $token);//随机数

        return $this->view->fetch();
    } 



    /**
     * 获取用户信息，没有授权的自动授权，类似登录
     * 
     * @return void
     */
    public function pc_callback($wx_token=null)
    {
        if($wx_token){
            Session::set('wx_token',$wx_token);
        }
        $app = $this->app;
        $oauth = $app->oauth;

        // 未登录或没openid数据的
        if (empty(Session::get('wechat_user'))) {
            
            $url = $this->request->domain().'/cms/user/code';//改成当前类的 访问路径，可以写成封装方法，怕一些用户看不懂
            $oauth->scopes(['snsapi_userinfo'])->redirect($url);//获取用户信息跳转
            //非Tp框架的可能要return
            
            // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用
            $oauth->redirect()->send();
            exit();
        }
        
        //上面是没有缓存信息，就进入授权  下面是有缓存执行的下面其实可以不用写
        $user = Session::get('wechat_user');
        //查询$wx_token
        $res = Db::name('pc_login')->where('token',Session::get('wx_token'))->update(['status'=>'2','openid'=>$user['openid'],'scan_time'=>time(),'scan_ip'=>$this->request->ip()]);

        $this->success('登陆成功',Config::get('site.scan_code_herf_url')??'/cms/wechat/wx_gz');

    }

    /**
     * 手机登陆后跳到微信号关注
     *
     * @return void
     */
    public function wx_gz()
    {
        $app = $this->app;
        $qrcode = $app->qrcode;
        $token = time().rand(11111,99999);
        $result = $qrcode->temporary($token, 600);
        $ticket = $result['ticket'];// 或者 $result['ticket']
        $url = $qrcode->url($ticket);
    
        $this->view->assign('qr', $url);//二维码
        return $this->view->fetch();
    } 


     /**
     * 消息
     *
     * @return void
     */
    public function msg($id=null)
    {
        if(!$id){
            $this->error('非法提交');
        }
        $id = base64_decode($id);
        $data = Db::name('msg')->where('id',$id)->find();
        if(!$data){
            $this->error('没有该数据');
        }

        $this->view->assign('data', $data);
        return $this->view->fetch();
    } 




    
}
